<?php
/**
 * 语法检查管理界面
 * Syntax Checker Admin Interface
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 语法检查管理界面类
 */
class WBW_Syntax_Checker_Admin {
    
    private $syntax_checker;
    private $performance_checker;
    private $auto_fix_engine;
    private $report_generator;
    private $db_manager;
    
    public function __construct() {
        $this->init_components();
        $this->init_hooks();
    }
    
    /**
     * 初始化组件
     */
    private function init_components() {
        require_once get_template_directory() . '/inc/syntax-checker.php';
        require_once get_template_directory() . '/inc/performance-checker.php';
        require_once get_template_directory() . '/inc/auto-fix-engine.php';
        require_once get_template_directory() . '/inc/report-generator.php';
        require_once get_template_directory() . '/inc/database-manager.php';
        
        $this->syntax_checker = new WBW_Syntax_Checker();
        $this->performance_checker = new WBW_Performance_Checker();
        $this->auto_fix_engine = new WBW_Auto_Fix_Engine();
        $this->report_generator = new WBW_Report_Generator();
        $this->db_manager = new WBW_Database_Manager();
    }
    
    /**
     * 初始化钩子
     */
    private function init_hooks() {
        if (current_user_can('manage_options')) {
            add_action('admin_menu', array($this, 'add_admin_menu'));
            add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
            
            // Ajax处理器
            add_action('wp_ajax_wbw_run_syntax_check', array($this, 'ajax_run_syntax_check'));
            add_action('wp_ajax_wbw_run_performance_check', array($this, 'ajax_run_performance_check'));
            add_action('wp_ajax_wbw_auto_fix_issues', array($this, 'ajax_auto_fix_issues'));
            add_action('wp_ajax_wbw_get_check_history', array($this, 'ajax_get_check_history'));
            add_action('wp_ajax_wbw_apply_optimizations', array($this, 'ajax_apply_optimizations'));
        }
    }
    
    /**
     * 添加管理菜单
     */
    public function add_admin_menu() {
        add_submenu_page(
            'themes.php',
            'WP Bootstrap Woo 语法检查',
            '语法检查',
            'manage_options',
            'wbw-syntax-checker',
            array($this, 'admin_page')
        );
    }
    
    /**
     * 加载管理脚本
     */
    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'appearance_page_wbw-syntax-checker') {
            return;
        }
        
        wp_enqueue_script('jquery');
        wp_enqueue_style('wbw-syntax-checker-admin', get_template_directory_uri() . '/assets/css/admin-syntax-checker.css');
        
        // 内联样式
        $custom_css = '
        .wbw-syntax-checker { margin: 20px 0; }
        .check-controls { margin: 20px 0; padding: 20px; background: #f1f1f1; border-radius: 5px; }
        .check-controls button { margin-right: 10px; }
        .results-container { margin: 20px 0; }
        .result-section { margin: 15px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .result-section h4 { margin-top: 0; }
        .success { color: #46b450; }
        .error { color: #dc3232; }
        .warning { color: #ffb900; }
        .loading { opacity: 0.6; }
        .recommendations { background: #fff; border-left: 4px solid #00a0d2; padding: 15px; }
        .recommendation-item { margin: 10px 0; padding: 10px; background: #f8f9fa; border-radius: 3px; }
        .priority-high { border-left: 4px solid #dc3232; }
        .priority-medium { border-left: 4px solid #ffb900; }
        .priority-low { border-left: 4px solid #46b450; }
        ';
        wp_add_inline_style('wbw-syntax-checker-admin', $custom_css);
    }
    
    /**
     * 管理页面
     */
    public function admin_page() {
        ?>
        <div class="wrap wbw-syntax-checker">
            <h1>WordPress主题语法检查系统</h1>
            
            <div class="check-controls">
                <h3>检查控制面板</h3>
                <button id="run-complete-check" class="button button-primary">运行完整检查</button>
                <button id="run-syntax-only" class="button">仅语法检查</button>
                <button id="run-performance-only" class="button">仅性能检查</button>
                <button id="auto-fix-issues" class="button button-secondary">自动修复问题</button>
                <button id="apply-optimizations" class="button button-secondary">应用性能优化</button>
                
                <div style="margin-top: 15px;">
                    <label>
                        <input type="checkbox" id="auto-fix-enabled"> 启用自动修复
                    </label>
                    <label style="margin-left: 20px;">
                        <input type="checkbox" id="create-backup"> 创建备份
                    </label>
                    <label style="margin-left: 20px;">
                        <input type="checkbox" id="detailed-report" checked> 详细报告
                    </label>
                </div>
            </div>
            
            <div id="progress-indicator" style="display: none;">
                <div class="notice notice-info">
                    <p>🔄 正在检查中，请稍候...</p>
                    <div style="background: #ddd; height: 10px; border-radius: 5px; margin: 10px 0;">
                        <div id="progress-bar" style="background: #0073aa; height: 100%; width: 0%; border-radius: 5px; transition: width 0.3s;"></div>
                    </div>
                </div>
            </div>
            
            <div id="results-container" class="results-container">
                <!-- 检查结果将在这里显示 -->
            </div>
            
            <div class="history-section">
                <h3>检查历史</h3>
                <button id="load-history" class="button">查看历史记录</button>
                <div id="history-container"></div>
            </div>
        </div>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            var isChecking = false;
            
            // 运行完整检查
            $('#run-complete-check').click(function() {
                runCheck('complete');
            });
            
            // 仅语法检查
            $('#run-syntax-only').click(function() {
                runCheck('syntax');
            });
            
            // 仅性能检查
            $('#run-performance-only').click(function() {
                runCheck('performance');
            });
            
            // 自动修复
            $('#auto-fix-issues').click(function() {
                if (confirm('确定要自动修复检测到的问题吗？这将创建备份并修改文件。')) {
                    runAutoFix();
                }
            });
            
            // 应用优化
            $('#apply-optimizations').click(function() {
                if (confirm('确定要应用性能优化设置吗？')) {
                    applyOptimizations();
                }
            });
            
            // 加载历史
            $('#load-history').click(function() {
                loadHistory();
            });
            
            function runCheck(type) {
                if (isChecking) return;
                
                isChecking = true;
                showProgress();
                
                var data = {
                    action: 'wbw_run_syntax_check',
                    check_type: type,
                    auto_fix: $('#auto-fix-enabled').is(':checked'),
                    create_backup: $('#create-backup').is(':checked'),
                    detailed_report: $('#detailed-report').is(':checked'),
                    nonce: '<?php echo wp_create_nonce('wbw_syntax_check_nonce'); ?>'
                };
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            displayResults(response.data);
                        } else {
                            displayError(response.data || '检查失败');
                        }
                    },
                    error: function() {
                        displayError('网络错误，请重试');
                    },
                    complete: function() {
                        isChecking = false;
                        hideProgress();
                    }
                });
            }
            
            function runAutoFix() {
                showProgress();
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wbw_auto_fix_issues',
                        nonce: '<?php echo wp_create_nonce('wbw_auto_fix_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('自动修复完成！');
                            runCheck('syntax'); // 重新检查
                        } else {
                            alert('自动修复失败: ' + (response.data || '未知错误'));
                        }
                    },
                    complete: function() {
                        hideProgress();
                    }
                });
            }
            
            function applyOptimizations() {
                showProgress();
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wbw_apply_optimizations',
                        optimization_types: ['css_optimize', 'js_optimize', 'lazy_load'],
                        nonce: '<?php echo wp_create_nonce('wbw_optimization_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('性能优化设置已应用！');
                            runCheck('performance'); // 重新检查
                        } else {
                            alert('应用优化失败: ' + (response.data || '未知错误'));
                        }
                    },
                    complete: function() {
                        hideProgress();
                    }
                });
            }
            
            function loadHistory() {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wbw_get_check_history',
                        limit: 20,
                        nonce: '<?php echo wp_create_nonce('wbw_history_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            displayHistory(response.data);
                        }
                    }
                });
            }
            
            function showProgress() {
                $('#progress-indicator').show();
                $('.check-controls button').prop('disabled', true).addClass('loading');
                animateProgress();
            }
            
            function hideProgress() {
                $('#progress-indicator').hide();
                $('.check-controls button').prop('disabled', false).removeClass('loading');
                $('#progress-bar').css('width', '0%');
            }
            
            function animateProgress() {
                var width = 0;
                var interval = setInterval(function() {
                    width += 2;
                    $('#progress-bar').css('width', width + '%');
                    if (width >= 100) {
                        clearInterval(interval);
                        width = 0;
                        $('#progress-bar').css('width', '0%');
                        animateProgress();
                    }
                }, 100);
            }
            
            function displayResults(data) {
                var html = '<div class="result-section">';
                html += '<h3>检查结果摘要</h3>';
                
                if (data.summary) {
                    html += '<p>总检查项: ' + data.summary.total_checks + '</p>';
                    html += '<p>错误数: <span class="error">' + data.summary.errors + '</span></p>';
                    html += '<p>警告数: <span class="warning">' + data.summary.warnings + '</span></p>';
                    html += '<p>成功率: ' + data.summary.success_rate + '%</p>';
                }
                
                html += '</div>';
                
                if (data.results && data.results.length > 0) {
                    html += '<div class="result-section"><h4>详细结果</h4>';
                    data.results.forEach(function(result) {
                        if (result.type === 'section') {
                            html += '<h4>' + result.title + '</h4>';
                        } else {
                            html += '<p class="' + result.type + '">' + result.message + '</p>';
                        }
                    });
                    html += '</div>';
                }
                
                if (data.optimization_suggestions && data.optimization_suggestions.length > 0) {
                    html += '<div class="recommendations">';
                    html += '<h4>优化建议</h4>';
                    data.optimization_suggestions.forEach(function(suggestion) {
                        html += '<div class="recommendation-item priority-' + suggestion.priority + '">';
                        html += '<h5>' + suggestion.title + '</h5>';
                        html += '<p>' + suggestion.description + '</p>';
                        if (suggestion.actions) {
                            html += '<ul>';
                            suggestion.actions.forEach(function(action) {
                                html += '<li>' + action + '</li>';
                            });
                            html += '</ul>';
                        }
                        html += '</div>';
                    });
                    html += '</div>';
                }
                
                $('#results-container').html(html);
            }
            
            function displayError(message) {
                var html = '<div class="notice notice-error"><p>检查失败: ' + message + '</p></div>';
                $('#results-container').html(html);
            }
            
            function displayHistory(data) {
                var html = '<table class="wp-list-table widefat fixed striped">';
                html += '<thead><tr><th>时间</th><th>类型</th><th>状态</th><th>文件</th><th>错误信息</th></tr></thead>';
                html += '<tbody>';
                
                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        html += '<tr>';
                        html += '<td>' + item.check_time + '</td>';
                        html += '<td>' + item.check_category + '</td>';
                        html += '<td><span class="' + item.status + '">' + item.status + '</span></td>';
                        html += '<td>' + (item.file_path || '') + '</td>';
                        html += '<td>' + (item.error_message || '') + '</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="5">暂无历史记录</td></tr>';
                }
                
                html += '</tbody></table>';
                $('#history-container').html(html);
            }
        });
        </script>
        <?php
    }
    
    /**
     * Ajax: 运行语法检查
     */
    public function ajax_run_syntax_check() {
        if (!wp_verify_nonce($_POST['nonce'], 'wbw_syntax_check_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        $check_type = sanitize_text_field($_POST['check_type'] ?? 'complete');
        $auto_fix = isset($_POST['auto_fix']) && $_POST['auto_fix'] === 'true';
        $create_backup = isset($_POST['create_backup']) && $_POST['create_backup'] === 'true';
        
        try {
            if ($check_type === 'syntax' || $check_type === 'complete') {
                $syntax_results = $this->syntax_checker->run_complete_check(array(
                    'auto_fix' => $auto_fix,
                    'create_backup' => $create_backup
                ));
            } else {
                $syntax_results = array();
            }
            
            if ($check_type === 'performance' || $check_type === 'complete') {
                $performance_results = $this->performance_checker->run_performance_check();
            } else {
                $performance_results = array();
            }
            
            $report = $this->report_generator->generate_complete_report($syntax_results, $performance_results);
            
            wp_send_json_success($report);
            
        } catch (Exception $e) {
            wp_send_json_error('检查过程中发生错误: ' . $e->getMessage());
        }
    }
    
    /**
     * Ajax: 应用优化设置
     */
    public function ajax_apply_optimizations() {
        if (!wp_verify_nonce($_POST['nonce'], 'wbw_optimization_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        $optimization_types = $_POST['optimization_types'] ?? array();
        
        try {
            $results = $this->performance_checker->apply_auto_optimizations($optimization_types);
            wp_send_json_success($results);
        } catch (Exception $e) {
            wp_send_json_error('应用优化失败: ' . $e->getMessage());
        }
    }
    
    /**
     * Ajax: 获取检查历史
     */
    public function ajax_get_check_history() {
        if (!wp_verify_nonce($_POST['nonce'], 'wbw_history_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        $limit = intval($_POST['limit'] ?? 20);
        $history = $this->db_manager->get_check_history($limit);
        
        wp_send_json_success($history);
    }
}

// 初始化管理界面
if (is_admin()) {
    new WBW_Syntax_Checker_Admin();
}